//
//  TicketBusinessListController.m
//  ELife
//
//  Created by xiaozhi on 11-7-23.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "TicketBusinessListController.h"
#import "UIViewUtil.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "ELifeAppDelegate.h"
#import "TicketBusinessModel.h"
#import "GetMyData.h"
#import "TicketBusinessDetailController.h"

@implementation TicketBusinessListController
@synthesize cityCode, detailList;

#pragma mark - network

- (void)requestDetailList:(NSInteger)index
{
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"ticket.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_ticket_by_type" forKey:@"action"];
    [param setObject:cityCode forKey:@"city"];
    [param setObject:[_typeList objectAtIndex:index] forKey:@"type"];
    [param setObject:@"6" forKey:@"limit"];
    [param setObject:@"1" forKey:@"page"];
    [param setObject:[GetMyData getClientVersion] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    [param release];
}

- (void)requestFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];  
    NSLog(@"root:%@", rootElement);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    GDataXMLElement* ticketsElement = [[bodyElement elementsForName:@"tickets"]objectAtIndex:0];
    NSArray* ticketElementList = [ticketsElement elementsForName:@"ticket"];
    
    NSInteger count = [ticketElementList count];
    _ticketModelList = [[NSMutableArray alloc] initWithCapacity:count];
    _imgArr = [[NSMutableArray alloc] initWithCapacity:count];

    for (NSInteger index = 0; index < count; index++) {
        GDataXMLElement* ticketElement = [ticketElementList objectAtIndex:index];
        
        TicketBusinessModel *model = [[TicketBusinessModel alloc] init];
        model.goods_id = [[[ticketElement elementsForName:@"goods_id"]objectAtIndex:0] stringValue];
        model.goods_name = [[[ticketElement elementsForName:@"goods_name"]objectAtIndex:0] stringValue];
        model.goods_catalogid = [[[ticketElement elementsForName:@"goods_catalogid"]objectAtIndex:0] stringValue];
        model.goods_price = [[[ticketElement elementsForName:@"goods_price"]objectAtIndex:0] stringValue];
        model.goods_price_pay = [[[ticketElement elementsForName:@"goods_price_pay"]objectAtIndex:0] stringValue];
        model.goods_smallpic = [[[ticketElement elementsForName:@"goods_smallpic"]objectAtIndex:0] stringValue];
        model.goods_client_smallpic = [[[ticketElement elementsForName:@"goods_client_smallpic"]objectAtIndex:0] stringValue];
        model.goods_pics = [[[ticketElement elementsForName:@"goods_pics"]objectAtIndex:0] stringValue];
        model.goods_brief = [[[ticketElement elementsForName:@"goods_brief"]objectAtIndex:0] stringValue];
        model.goods_desc = [[[ticketElement elementsForName:@"goods_desc"]objectAtIndex:0] stringValue];
        model.goods_detail = [[[ticketElement elementsForName:@"goods_detail"]objectAtIndex:0] stringValue];
        model.ticket_time = [[[ticketElement elementsForName:@"ticket_time"]objectAtIndex:0] stringValue];
        
        // request img
        @synchronized(lock) {
            UIImage *image = [UIImage alloc];
            [[[ELifeAppDelegate App] httpRequestPoint]getImageDataByUrl:model.goods_smallpic forUIImage:image delegate:self];
            [_imgArr addObject:image];
            
            [_ticketModelList addObject:model];
            [model release];

        }
    }
    
    [detailList setHidden:YES];
    
    if ([_ticketModelList count] > 0) {
        [detailList setHidden:NO];
    }   
    
    [detailList reloadData];
}

- (void)iRequestFailed
{
    [[ELifeAppDelegate App] hideProgressDialog];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        /*
         'tuijian' => '热门推荐',
         'huaju' => '话剧',
         'yanchanghui' => '演唱会',
         'xiangsheng' => '相声',
         'tiyu' => '体育',
         */
        _typeList = [[NSArray arrayWithObjects:@"tuijian",
                     @"huaju",
                     @"yanchanghui",
                     @"xiangsheng",
                     @"tiyu",
                     nil] retain];
    }
    return self;
}

- (void)dealloc
{
    [_typeList release];
    [_ticketModelList release];
    [cityCode release];
    [detailList release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIViewUtil getCommonBg];

    lock = [[NSObject alloc] init];
    [detailList setRowHeight:110];
    
    [detailList setHidden:YES];
    
    [self requestDetailList:0];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - tableView datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_ticketModelList count];
}


- (void)fillCell:(UITableViewCell *)cell withModel:(TicketBusinessModel *)model
{
    NSString *timeAndAddress = model.ticket_time;
    NSArray *timeAndAddressArray = [timeAndAddress componentsSeparatedByString:@"|"];
    NSString *time = [timeAndAddressArray objectAtIndex:0];
    NSString *address = [timeAndAddressArray objectAtIndex:1];
    NSString *title = model.goods_name;
    
    UILabel *timeLabel = (UILabel *)[cell viewWithTag:102];
    UILabel *addressLabel = (UILabel *)[cell viewWithTag:103];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:105];
    
    [timeLabel setText:time];
    [addressLabel setText:address];
    [titleLabel setText:title];
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TicketBusinessModel *model = [_ticketModelList objectAtIndex:indexPath.row];
    static NSString *identifier = @"cell"; 
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        static NSString *nibName = @"TicketBusinessCell";
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.backgroundColor = [UIColor whiteColor];
        [UIViewUtil viewRoundFrame:cell];
    }

    [self fillCell:cell withModel:model];
    
    UIImageView *imageView = (UIImageView *)[cell viewWithTag:101];
    @synchronized(lock){
        if (indexPath.row < [_imgArr count]) {
            NSInteger index = indexPath.row;
            imageView.image = [_imgArr objectAtIndex:index];
            
        }

    }
    return cell;
}

#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TicketBusinessModel *model = [_ticketModelList objectAtIndex:indexPath.row];
    
    TicketBusinessDetailController *detailController = [[TicketBusinessDetailController alloc] initWithTicketBusinessModel:model];
    [self.navigationController pushViewController:detailController animated:YES];
    [detailController release];
}

- (void)changeTab:(id)sender
{
    UISegmentedControl *segmentControl = (UISegmentedControl *)sender;
    NSInteger focusIndex = [segmentControl selectedSegmentIndex];
    if (focusIndex != _segmentFocusIndex) {
        _segmentFocusIndex = focusIndex;
        _imgArr = nil;
        [self requestDetailList:focusIndex];
    }
}

/*
 refresh img
 */
- (void)refreshImage
{
    [detailList reloadData];
}

@end
